package generator.service.impl;

import com.atkt.ktkt.model.vod.Chapter;
import com.atkt.ktkt.model.vod.Video;
import com.atkt.ktkt.vo.vod.ChapterVo;
import com.atkt.ktkt.vo.vod.VideoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import generator.service.ChapterService;
import generator.mapper.ChapterMapper;
import generator.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 罗雅文
 * @description 针对表【chapter(课程)】的数据库操作Service实现
 * @createDate 2022-09-18 17:24:58
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter>
        implements ChapterService {

    @Autowired
    private VideoService videoService;

    /**
     * 1.大纲列表 （章节和小节列表）
     *
     * @param courseId
     * @return
     */
    @Override
    public List<ChapterVo> getTreeList(Long courseId) {
        List<ChapterVo> finalChapterList = new ArrayList<>();

        // 根据courseId获取课程里面所有章节
        LambdaQueryWrapper<Chapter> wrapperChapter = new LambdaQueryWrapper<>();
        wrapperChapter.eq(Chapter::getCourseId, courseId);
        List<Chapter> chapters = baseMapper.selectList(wrapperChapter);

        //根据courseId获取课程里面所有小节
        LambdaQueryWrapper<Video> wrapperVideo = new LambdaQueryWrapper<>();
        wrapperVideo.eq(Video::getCourseId, courseId);
        List<Video> videoList = videoService.list(wrapperVideo);

        //封装章节
        for (int i = 0; i < chapters.size(); i++) {
            Chapter chapter = chapters.get(i); //得到每个章节
            //chapter -> chapterVo
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);  //浅复制 不能复制数组和集合
            finalChapterList.add(chapterVo);  //对象仍然是同一个对象 基本在后封装 照样不变能加

            //封装章节里的小节
            ArrayList<VideoVo> videoVos = new ArrayList<>();
            videoList.forEach(video -> {
                //判断小节是哪个章节下面
                //章节id 和 chapter_id
                if (chapter.getId().equals(video.getChapterId())) {
                    //video -> videoVo
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    //放 videoVoList
                    videoVos.add(videoVo);
                }
            });
            //把章节里面所有的小节集合 放到每个章节里面
            chapterVo.setChildren(videoVos);
        }
        return  finalChapterList;
    }

    //根据课程id删除章节
    @Override
    public void removeChapterByCourseId(Long id) {
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getCourseId,id);
        baseMapper.delete(wrapper);
    }

    @Override
    public List<ChapterVo> getNestedTreeList(Long id) {
        return null;
    }
}




